// add you code here
module keyboard(input clk,
	input clrn,
	input ps2_clk,
	input ps2_data,
	output reg [7:0] key_count=0,
	output reg [7:0] cur_key=0,
	output [7:0] ascii_key,
	output mode,
	output _ready);

reg [2:0]head=0;
reg [2:0]tail=0;

reg [7:0]key_buffer[2:0];

reg [2:0] ps2_clk_sync;
always @(posedge clk) begin
    ps2_clk_sync <=  {ps2_clk_sync[1:0],ps2_clk};
end
wire sampling = ps2_clk_sync[2] & ~ps2_clk_sync[1];
reg [3:0] count_clk = 0;
reg clk_key = 1;
always @(posedge clk) begin
	if(sampling) begin
		if(count_clk == 10)
		begin
			count_clk <= 0;
			clk_key <= 0;
		end
		else begin
			count_clk <= count_clk + 1;
            clk_key <= 1;
        end
	end
end
reg nextdata_n=0;
wire [7:0] keydata;
assign _ready = ready;
wire ready;
wire overflow;
reg flag=1'b1;
reg flag1=1'b1;
reg flag2=1'b0; //0 for visual, 1 for input
reg flag3=1'b0;
reg flag4=1'b0;
reg [7:0] lastkeydata;
always @(negedge clk) begin
	 if(clk_key==0) begin
	 if(clrn == 0) key_count <= 0;
	 else if (ready) begin
	 	 lastkeydata<=keydata;
		if(keydata != 8'hf0 && flag) begin
			if(cur_key==8'h12) begin
				flag3=1'b1;
				flag4=1'b1;
			end
			cur_key <= keydata;
			flag <= 1;
         flag1 <= 0;
		end
		else if (keydata == 8'hf0) begin
				if(cur_key==8'h58) flag2=~flag2;
            cur_key <= 0;
				flag <= 0;
            flag1 <= 1;
		end
		else if(!flag) begin
			flag <= 1;
		end
		nextdata_n <= 0;
	end
	else begin
			nextdata_n <= 1;
	end
		if(flag4==1 && keydata==8'h12 && lastkeydata==8'hf0) begin
			flag3=0;
			flag4=0;
		end
	end
end

assign mode=flag2;
scancode_ram myram(flag3, 0, clk, cur_key, ascii_key);
ps2_keyboard mykey(clk, clrn, ps2_clk, ps2_data, keydata, ready, nextdata_n, overflow);
endmodule